package com.ufo.store.management.net;

import android.app.Activity;
import android.text.TextUtils;

import com.ufo.store.management.BarApplication;
import com.yanzhenjie.nohttp.BasicBinary;
import com.yanzhenjie.nohttp.FileBinary;
import com.yanzhenjie.nohttp.Logger;
import com.yanzhenjie.nohttp.NoHttp;
import com.yanzhenjie.nohttp.OnUploadListener;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.error.NetworkError;
import com.yanzhenjie.nohttp.error.NotFoundCacheError;
import com.yanzhenjie.nohttp.error.TimeoutError;
import com.yanzhenjie.nohttp.error.URLError;
import com.yanzhenjie.nohttp.error.UnKnownHostError;
import com.yanzhenjie.nohttp.rest.OnResponseListener;
import com.yanzhenjie.nohttp.rest.Request;
import com.yanzhenjie.nohttp.rest.RequestQueue;
import com.yanzhenjie.nohttp.rest.Response;

import com.ufo.store.management.R;
import com.ufo.store.management.utils.ToastUtils;
import com.ufo.store.management.widget.dialog.WaitDialog;

import java.io.File;
import java.util.HashMap;
import java.util.Map;


/**
 * 上传
 */
public class UploadServer {

    private static UploadServer instance;

    public static UploadServer getInstance() {
        if (instance == null)
            synchronized (UploadServer.class) {
                if (instance == null) {
                    instance = new UploadServer();
                }
            }
        return instance;
    }

    private RequestQueue mQueue;

    private UploadServer() {
        mQueue = NoHttp.newRequestQueue(1);
    }

    /**
     * 单个文件上传监听的标志。
     */
    private final int WHAT_UPLOAD_SINGLE = 0xA1;

    /**
     * 进度条。
     */
    WaitDialog mWaitDialog;

    /**
     * 文件上传监听。
     */
    private OnUploadListener mOnUploadListener = new OnUploadListener() {

        @Override
        public void onStart(int what) {// 这个文件开始上传。

        }

        @Override
        public void onCancel(int what) {// 这个文件的上传被取消时。
            ToastUtils.show(R.string.upload_cancel);
        }

        @Override
        public void onProgress(int what, int progress) {// 这个文件的上传进度发生边耍

        }

        @Override
        public void onFinish(int what) {// 这个文件的上传结束

        }

        @Override
        public void onError(int what, Exception exception) {// 文件上传发生错误。
            ToastUtils.show(R.string.upload_error);
        }
    };

    /**
     * 上传单个文件。
     */
    public void uploadFile(final Activity context, String url, String filePath, Map<String, Object> map, final String msg, final NetCallback<String> callBack, final Class<?> rspCls) {
        Request<String> request = NoHttp.createStringRequest(url, RequestMethod.POST);
        // 添加请求参数。
        if (map == null) {
            map = new HashMap<>();
        }
        // 上传文件需要实现NoHttp的Binary接口，NoHttp默认实现了FileBinary、InputStreamBinary、ByteArrayBitnary、BitmapBinary。
        File file = new File(filePath);
        if( !file.exists()){
            return;
        }
        BasicBinary binary = new FileBinary(file);

        /**
         * 监听上传过程，如果不需要监听就不用设置。
         * 第一个参数：what，what和handler的what一样，会在回调被调用的回调你开发者，作用是一个Listener可以监听多个文件的上传状态。
         * 第二个参数： 监听器。
         */
        binary.setUploadListener(WHAT_UPLOAD_SINGLE, mOnUploadListener);

        //添加POST请求参数
        request.add("file", binary);
        request.add(map);

        String token = BarApplication.apptoken;
        if (!TextUtils.isEmpty(token)) {
            request.addHeader("Authorization", "bearer " + token);
        }

        mQueue.add(WHAT_UPLOAD_SINGLE, request, new OnResponseListener<String>() {
            @Override
            public void onStart(int what) {
                if (!TextUtils.isEmpty(msg)) {
                    mWaitDialog = new WaitDialog(context);
                    mWaitDialog.setMessage(msg);
                    mWaitDialog.setOwnerActivity(context);
                    mWaitDialog.setCancelable(true);
                    mWaitDialog.show();
                }
            }

            @Override
            public void onSucceed(int what, Response<String> response) {
                String result = response.get();
                if ( !TextUtils.isEmpty(result)) {
                    callBack.onSucceed(result);
                } else {
                    callBack.onFailed(context.getString(R.string.error_data));
                }
            }

            @Override
            public void onFinish(int what) {
                if (mWaitDialog != null && mWaitDialog.isShowing()) {
                    Activity activity = mWaitDialog.getOwnerActivity();
                    if (activity != null && !activity.isFinishing()) {
                        mWaitDialog.dismiss();
                    }
                }
            }

            @Override
            public void onFailed(int what, Response<String> response) {
                // 请求失败
                Throwable exception = response.getException();
                if (exception instanceof NetworkError) {// 网络不好
                    ToastUtils.show(R.string.error_please_check_network);
                } else if (exception instanceof TimeoutError) {// 请求超时
                    ToastUtils.show(R.string.error_timeout);
                } else if (exception instanceof UnKnownHostError) {// 找不到服务器
                    ToastUtils.show(R.string.error_not_found_server);
                } else if (exception instanceof URLError) {// URL是错的
                    ToastUtils.show(R.string.error_url_error);
                } else if (exception instanceof NotFoundCacheError) {
                    // 这个异常只会在仅仅查找缓存时没有找到缓存时返回
                    ToastUtils.show(R.string.error_not_found_cache);
                } else {
                    ToastUtils.show(R.string.error_unknow);
                }
                Logger.e(exception.getMessage());
                callBack.onFailed(response.getException().getMessage());
            }
        });
    }
}